<template>
	<view class="create_business_card_wrap">
		<!-- tabs -->
		<view class="tabs_box">
			<wd-tabs v-model="tab">
				<block v-for="(item, indexI) in tabs" :key="indexI">
					<wd-tab :title="item.title">
						<!-- <view :class="`content ${item.name}`"></view> -->
					</wd-tab>
				</block>
			</wd-tabs>
		</view>

		<!-- form box -->
		<!-- 个人资料表单 -->
		<view class="form_box personal_data_form_box" v-if="tab == 0">
			<!-- 基本信息 -->
			<view class="base_info">
				<wd-card>
					<!-- 头像 -->
					<view class="form_item_box avatar">
						<text class="label">
							<text class="required_fields">*</text>
							头像
						</text>
						<!-- 	<view class="avatar_img">
							<wd-img :width="50" :height="50" round :src="personalFormData.avatar" />
						</view> -->
						<wd-img-cropper v-model="avatarShow" :img-src="avatarSrc" @confirm="avatarHandleConfirm" @cancel="handleCancel('头像')"></wd-img-cropper>
						<view class="profile">
							<view v-if="personalFormData.avatar == '' || personalFormData.avatar == null || personalFormData.avatar == undefined" class="img" @click="avatarUpload">
								<wd-icon name="fill-camera" custom-class="img-icon"></wd-icon>
							</view>
							<wd-img
								v-if="personalFormData.avatar"
								round
								width="50px"
								height="50px"
								:src="personalFormData.avatar"
								mode="widthFix"
								custom-class="profile-img"
								@click="avatarUpload"
							>
								<template #loading>
									<view class="loading-wrap">
										<wd-loading />
									</view>
								</template>
							</wd-img>
						</view>
					</view>

					<!-- 姓名 -->
					<view class="form_item_box">
						<text class="label">
							<text class="required_fields">*</text>
							姓名
						</text>
						<view class="input_box">
							<wd-input type="text" no-border v-model="personalFormData.name" placeholder="请输入姓名" />
						</view>
					</view>

					<!-- 职位 -->
					<view class="form_item_box">
						<text class="label">
							<text class="required_fields">*</text>
							职位
						</text>
						<view class="input_box">
							<wd-input type="text" no-border v-model="personalFormData.position" placeholder="请输入职位" />
						</view>
					</view>

					<!-- 手机号 -->
					<view class="form_item_box">
						<text class="label">
							<text class="required_fields">*</text>
							手机号
						</text>
						<view class="input_box tel_num_right_box">
							<wd-input style="margin-right: 20px;" type="number" custom-class="phone_input" no-border v-model="personalFormData.phone" placeholder="请输入手机号" />
							<text style="display: inline-block;width: 10px;"></text>
							<wd-button  style="padding: 0px 10px;" custom-class="getPhone_btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" type="primary" hairline plain >获取手机号</wd-button>
						</view>
					</view>

					<!-- 微信号 -->
					<view class="form_item_box">
						<text class="label">微信号</text>
						<view class="input_box">
							<wd-input type="text" no-border v-model="personalFormData.wxNumber" placeholder="请输入微信号" />
						</view>
					</view>

					<!-- 微信二维码 -->
					<view class="form_item_box wx_qr_code">
						<text class="label">微信二维码</text>
						<!-- <wd-img
						 :width="80"
						 :height="80"
						 :src="personalFormData.wxQrCode"
						/> -->

						<wd-img-cropper v-model="wxQrCodeShow" :img-src="wxQrCodeSrc" @confirm="wxQrCodeHandleConfirm" @cancel="handleCancel('微信二维码')"></wd-img-cropper>
						<view class="profile">
							<view v-if="personalFormData.wxQrCode == '' || personalFormData.wxQrCode == null || personalFormData.wxQrCode == undefined" class="img" @click="wxQrCodeUpload">
								<wd-icon name="fill-camera" custom-class="img-icon"></wd-icon>
							</view>
							<wd-img
								v-if="personalFormData.wxQrCode"
								width="80px"
								height="80px"
								:src="personalFormData.wxQrCode"
								mode="widthFix"
								custom-class="profile-img"
								@click="wxQrCodeUpload"
							>
								<template #loading>
									<view class="loading-wrap">
										<wd-loading />
									</view>
								</template>
							</wd-img>
							<!-- <view style="font-size: 14px;">点击上传头像</view> -->
						</view>
					</view>

					<!-- 邮箱 -->
					<view class="form_item_box">
						<text class="label">邮箱</text>
						<view class="input_box">
							<wd-input type="text" no-border v-model="personalFormData.email" placeholder="请输入邮箱" />
						</view>
					</view>
				</wd-card>
			</view>

			<!-- 企业基本资料 -->
			<wd-card title="">
				<view class="company_base_info_box">
					<view class="form_item_box company_name">
						<text class="label">
							<text class="required_fields">*</text>
							公司
						</text>
						<text>{{personalFormData.companyName}}</text>
						<!-- <view class="input_box"> -->
							
							<!-- <wd-input type="text" no-border disabled v-model="personalFormData.companyName" placeholder="请输入公司名称" /> -->
						<!-- </view> -->
					</view>
					<view class="form_item_box company_address">
						<text class="label">
							<text class="required_fields">*</text>
							地址
						</text>
						<view class="input_box">
							<wd-input type="text" no-border @change="addressChange" v-model="personalFormData.companyAddress" placeholder="请输入公司地址" />
							<view class="select_location_box">
								<text class="select_location_text" @click="selectLocation">选择位置</text>
							</view>
						</view>
					</view>
					<view class="form_item_box company_industry">
						<text class="label">
							<text class="required_fields">*</text>
							行业
						</text>
						<!-- <wd-picker disabled :columns="industrySelectData" label="" v-model="personalFormData.industry" @confirm="industryConfirm" /> -->
						<text>{{ personalFormData.industry }}</text>
					</view>
					<view class="form_item_box">
						<text class="label">官网</text>
							<text>{{personalFormData.officialWebsite}}</text>
						<!-- <view class="input_box">
							<wd-input type="text" disabled no-border v-model="personalFormData.officialWebsite" placeholder="请输入公司官网" />
						</view> -->
					</view>
				</view>
			</wd-card>

			<!-- 公司信息 -->
			<!-- 	<view class="company_info">
				<wd-card class="">
					111
				</wd-card>
			</view> -->

			<!-- 个人介绍 -->
			<view class="self_introduction_box">
				<wd-card title="个人介绍">
					<hr />
					<wd-textarea v-model="personalFormData.selfIntroduction" placeholder="请介绍一下可爱的自己~" />
				</wd-card>
			</view>

			<!-- 我的相册 -->
			<!-- <wd-card title="我的相册">
				111
			</wd-card> -->
		</view>

		<!-- 企业资料表单 -->
		<view class="form_box enterprise_data_form_box" v-else>
			<!-- 公司LOGO -->
			<wd-card>
				<view class="logo_box">
					<text class="label">公司Logo</text>
					<view class="logo_upload_box">
						<!-- 	<wd-img-cropper v-model="logoShow" :img-src="logoSrc" @confirm="logoHandleConfirm" @cancel="handleCancel('公司logo')"></wd-img-cropper>
						<view class="profile">
							<view v-if="companyFormData.logoUrl == '' || companyFormData.logoUrl == null || companyFormData.logoUrl == undefined" class="img" @click="logoUpload">
								<wd-icon name="fill-camera" custom-class="img-icon"></wd-icon>
							</view>
							<wd-img v-if="companyFormData.logoUrl" width="50px" height="50px" :src="companyFormData.logoUrl" mode="widthFix" custom-class="profile-img" @click="logoUpload" >
								<template #loading>
								     <view class="loading-wrap">
								       <wd-loading/>
								     </view>
								   </template>
							</wd-img>
						</view> -->
						<!-- <image :src="fileList1.value[0]" mode="" v-if="fileList1.value[0]"></image> -->
						<wd-upload
							custom-class="logo_upload"
							style="width: 100px; height: 100px"
							:file-list="fileList1"
							image-mode="aspectFill"
							:action="`${baseUrl}/upload/image`"
							:limit="1"
							@change="handleChange1"
						></wd-upload>
					</view>
				</view>
			</wd-card>

			<ProductIntroduceCard></ProductIntroduceCard>

			<!-- 企业介绍展示 -->
			<!-- <wd-card title="企业介绍"></wd-card> -->
			<view class="company_introduce_box">
				<view class="header_box">
					<view class="left_box">
						<text class="label">企业介绍</text>
						<view class="add_company_introduce_box" @click="toEditCompanyIntroduce">
							<wd-icon name="add" size="18px" color="#f1f1f1"></wd-icon>
						</view>
					</view>
					<view class="right_box">
						<!-- <wd-button plain size="small" style="" @click="toEditCompanyIntroduce"><wd-icon name="edit-outline" style="margin-right: 4px;display: inline-block;" size="12px"></wd-icon>
						<text style="margin-left: 4px;">编辑企业介绍</text>
						</wd-button> -->
					</view>
				</view>
				<template v-if="cardStore.companyIntroduceList.length != 0">
					<view class="content_box" v-for="(ccil, indexCC) in cardStore.companyIntroduceList" :key="indexCC">
						<!-- 操作栏 -->
						<view class="introduce_action_box">
							<view class="introduce_action_item_box" @click="editCompanyIntroduceItemClick(ccil)">
								<wd-icon name="edit-1" size="16px" color="#f1f1f1"></wd-icon>
							</view>
							<view class="introduce_action_item_box" @click="delCompanyIntroduceItemClick(ccil)">
								<wd-icon name="delete1" size="16px" color="#f1f1f1"></wd-icon>
							</view>
						</view>
						<!-- 标题 -->
						<view class="title_box">
							<text class="title_text">{{ ccil.title }}</text>
						</view>
						<!-- 内容文本 -->
						<view class="content_text_box">
							<text class="content_text">{{ ccil.contentText }}</text>
						</view>
						<!-- 内容图片 -->
						<view class="imgs_box">
							<wd-img width="82vw" :height="200" v-for="(ccili, indexCi) in ccil.contentImages" :key="indexCi" :src="ccili" mode="widthFix" :enable-preview="true">
								<template #loading>
									<view class="loading-wrap">
										<wd-loading />
									</view>
								</template>
							</wd-img>
							<image class="imgs_item_img" v-for="(ccili, indexCi) in ccil.contentImages" :key="indexCi" :src="ccili" mode=""></image>
						</view>
					</view>
				</template>
				<view class="not_data" v-else>
					<text class="not_data_text">暂无介绍</text>
				</view>
				<view class="footer_box"></view>
			</view>
		</view>
		<!-- <button open-type="share">分享按钮</button> -->

		<!-- 
		<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
			<image class="avatar" :src="avatarSrcUrl" style="width: 100rpx;height: 100rpx;"></image>
		</button> -->

		<!-- 保存按钮盒子 -->
		<view class="save_btn_box">
			<!-- 个人资料保存 -->
			<wd-button v-if="tab == 0" type="primary" size="large" @click="userSaveClick">
				<text class="btn_content_text">保存</text>
			</wd-button>

			<!-- 企业资料保存 -->
			<wd-button v-else type="success" size="large" @click="companySaveClick">
				<text class="btn_content_text">保存</text>
			</wd-button>
		</view>

		<!-- 底部占位元素 -->
		<view class="bottom_placeholder_box"></view>

		<!-- 弹窗盒子 -->
		<wd-message-box />
	</view>
</template>

<script>
import { defineComponent, onMounted, ref } from 'vue'
import './index.scss'
export default defineComponent({
	name: 'CreateBusinessCard'
})
</script>
<script setup>
	
// import WXBizDataCrypt from './WXBizDataCrypt.js'
import { onShareAppMessage, onLoad } from '@dcloudio/uni-app'
import jsonData from './data/data.json'
import { useUserStore } from '@/stores/user.js'
import { useCardStore } from '@/stores/card.js'
import { selectCardCompanyApi, selectCardUserApi, addCardCompanyApi, addCardUserApi, editCardCompanyApi, editCardUserApi } from '@/api/card.js'
import { upLoadFileApi } from '@/api/file.js'
import { useMessage } from '@/uni_modules/wot-design-uni'
import { baseUrl } from '../../libs/baseUrl.js'
import ProductIntroduceCard from './components/productIntroduceCard.vue'

const message = useMessage()
const userStore = useUserStore()
const cardStore = useCardStore()

const fileList1 = ref([])

// 获取手机号令牌
const onGetPhoneNumber = (e) => {
	console.log('获取手机号', e)
// let pc = new WXBizDataCrypt('wxa83a95ff5502b74f', userStore.sessionKey);
// let data = pc.decryptData(e.encryptedData, e.iv);

	// let data = WXBizDataCrypt(e.encryptedData,e.iv)
	// console.log('data',data)
	// if (data.phoneNumber != '') {
	// 	this.phone = data.phoneNumber
	// }
	getUserPhone(e.code)
}

// 当前的accessToken
const accessToken = ref('')


// 获取access_token
const getAccess_token  = ()=>{
	uni.request({
		url:'https://api.weixin.qq.com/cgi-bin/token',
		method:'GET',
		data:{
			grant_type:'client_credential',
			appid:"wxa83a95ff5502b74f",
			secret:"107afdf1420d1dc15622b9747c18e263"
		},
		success: (res) => {
			console.log('获取token',res);
			accessToken.value = res.data.access_token
		}
	})
}

// 获取手机号
const getUserPhone = (code)=>{
	// uni.request({
	// 	url:`https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken.value}`,
	// 	method:"POST",
	// 	data:{
	// 		code:code
	// 	},
	// 	success: (res) => {
	// 	let phone = res.data.phone_info.phoneNumber
	// 	console.log('获取手机号请求phone',phone);
	// 	personalFormData.value.phone = phone
	// 	}
	// })
	uni.request({
		url:baseUrl+`/user/selectPhone?code=${code}`,
		method:"POST",
		success: (res) => {
			console.log('获取手机号res',res);
			let dataJ = JSON.parse(res.data.data)
			console.log('dataJ',JSON.parse(res.data.data));
			personalFormData.value.phone = JSON.parse(res.data.data).phone_info.phoneNumber
		}
		
	})
}



// const value = ref('')

const handleChange1 = (e) => {
	console.log('handleChange1', e)
	let logoUrl = JSON.parse(e.fileList[0].response).data
	fileList1.value = [
		{
			url: logoUrl
		}
	]
}

// 跳转到编辑企业介绍页
const toEditCompanyIntroduce = () => {
	uni.navigateTo({
		url: '/pages/editCompanyIntroduce/editCompanyIntroduce'
	})
	cardStore.isAdd = true
	cardStore.currentEditCompanyIntroduceInfo = {
		id: null,
		title: '',
		contentText: '',
		contentImages: []
	}
}

// 删除企业介绍项的点击事件
const delCompanyIntroduceItemClick = (item) => {
	console.log('删除项', item)
	message
		.confirm({
			msg: `是否删除-${item.title}`,
			title: '提示'
		})
		.then(() => {
			cardStore.companyIntroduceList = cardStore.companyIntroduceList.filter((itemC) => {
				return itemC.id != item.id
			})
			uni.showToast({
				title: '删除成功',
				mask: true,
				icon: 'none',
				duration: 1000
			})
		})
		.catch(() => {})
}

// 编辑企业介绍项的点击事件
const editCompanyIntroduceItemClick = (item) => {
	console.log('修改项', item)
	uni.navigateTo({
		url: '/pages/editCompanyIntroduce/editCompanyIntroduce'
	})
	cardStore.isAdd = false
	cardStore.currentEditCompanyIntroduceInfo = item
}

// onShareAppMessage(() => {
// 	return {
// 		title: 'wwl的名片',
// 		path: '/pages/businessCard/businessCard?userId=111'
// 	}
// })

// 个人资料表单数据
const personalFormData = ref({
	// 头像
	avatar: '',
	// 姓名
	name: '',
	// 职位
	position: '',
	// 手机号
	phone: '',
	// 微信号
	wxNumber: '',
	// 微信二维码
	wxQrCode: '',
	// 邮箱
	email: '',
	// 个人介绍
	selfIntroduction: '业务范围：饮用水安全监测 | 实验室定量分析 | 水环境质量监测 | 工业工程在线监测 | 污水排放水质监测 产品及解决方案咨询',
	// 公司名称
	companyName: '浙江陆恒环境科技有限公司',
	// 公司地址
	companyAddress: '',
	// 公司坐标lat
	lat: '',
	// 公司坐标lng
	lng: '',
	// 所属行业
	industry: '制造业',
	// 公司官网
	officialWebsite: 'www.lohand.com',
	// cardUserId
	cardUserId: null
})

// 企业资料表单数据
const companyFormData = ref({
	logoUrl: ''
})

// tabs数据
const tabs = ref([
	{
		title: '个人资料',
		name: 'personal_data'
	},
	{
		title: '企业资料',
		name: 'enterprise_data'
	}
])

onLoad(() => {
	// 动态展示tab
	if (userStore.isCreateBusinessCard) {
		tabs.value = [
			{
				title: '个人资料',
				name: 'personal_data'
			},
			{
				title: '企业资料',
				name: 'enterprise_data'
			}
		]
	} else {
		tabs.value = [
			{
				title: '个人资料',
				name: 'personal_data'
			}
		]
	}
})

// 当前企业ID
const currentCompanyId = ref(null)

// tab当前项
const tab = ref(0)

// 微信二维码上传图片相关变量
const wxQrCodeSrc = ref('')
const wxQrCodeShow = ref(false)

// const imgSrc = ref('')
// 头像上传图片相关变量
const avatarSrc = ref('')
const avatarShow = ref(false)

// 公司logo上传相关变量
const logoSrc = ref('')
const logoShow = ref(false)

// 微信二维码上传upload
function wxQrCodeUpload() {
	uni.chooseImage({
		count: 1,
		success: (res) => {
			// 获取文件的临时路径
			//  const tempFilePaths = res.tempFilePaths;
			// uni.compressImage({
			//      src: tempFilePaths[0], // 图片路径
			//      quality: 1, // 压缩质量，范围为0 - 100，100为不压缩
			//      success: (compressRes) => {
			//        // 获取压缩后的图片路径
			//        const compressedFilePath = compressRes.tempFilePath;
			// 			// const tempFilePaths = res.tempFilePaths[0]
			// 			wxQrCodeSrc.value = compressedFilePath
			// 			wxQrCodeShow.value = true
			//        // 执行上传操作
			//      },
			//      fail: (err) => {
			//        console.log('压缩失败', err);
			//      }
			//    });
			console.log('load-res', res)
			const tempFilePaths = res.tempFilePaths[0]
			wxQrCodeSrc.value = tempFilePaths
			wxQrCodeShow.value = true
		}
	})
}

// 头像上传upload
function avatarUpload() {
	console.log('11', 11)
	uni.chooseImage({
		count: 1,
		success: (res) => {
			console.log('load-res', res)
			const tempFilePaths = res.tempFilePaths[0]
			avatarSrc.value = tempFilePaths
			avatarShow.value = true
		}
	})
}

// logo上传upload
function logoUpload() {
	console.log('11', 11)
	uni.chooseImage({
		count: 1,
		success: (res) => {
			console.log('load-res', res)
			const tempFilePaths = res.tempFilePaths[0]
			logoSrc.value = tempFilePaths
			logoShow.value = true
		}
	})
}

// 微信二维码裁剪确定
function wxQrCodeHandleConfirm(event) {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	console.log('微信裁剪')
	const { tempFilePath } = event
	const fileSystemManager = uni.getFileSystemManager()
	let fileData
	fileSystemManager.readFile({
		filePath: tempFilePath, // 图片临时路径
		success: async (data) => {
			console.log('data', data)
			fileData = data.data
			// uploadFile(src, file).then((data) => {
			// 	resolve(data);
			// });
			await upLoadFileApi(tempFilePath)
				.then((res) => {
					console.log('上传微信二维码res', res)
					let rData = JSON.parse(res.data)
					console.log('rData', rData)
					personalFormData.value.wxQrCode = rData.data
					uni.hideLoading()
				})
				.catch((err) => {
					console.log('上传图片err', err)
					uni.showToast({
						title: '上传图片失败',
						icon: 'none',
						mask: true,
						duration: 1000
					})
				})
		},
		fail: (err) => {
			console.log('读取文件失败', err)
			uni.showToast({
				title: '读取文件失败',
				icon: 'none',
				mask: true,
				duration: 1000
			})
		}
	})
	// personalFormData.value.wxQrCode = tempFilePath
}

// 头像裁剪确定
function avatarHandleConfirm(event) {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	console.log('头像裁剪')
	const { tempFilePath } = event
	const fileSystemManager = uni.getFileSystemManager()
	let fileData
	fileSystemManager.readFile({
		filePath: tempFilePath, // 图片临时路径
		success: async (data) => {
			console.log('data', data)
			fileData = data.data
			// uploadFile(src, file).then((data) => {
			// 	resolve(data);
			// });
			await upLoadFileApi(tempFilePath)
				.then((res) => {
					console.log('上传头像res', res)
					let rData = JSON.parse(res.data)
					console.log('rData', rData)
					personalFormData.value.avatar = rData.data
					uni.hideLoading()
				})
				.catch((err) => {
					console.log('上传图片err', err)
					uni.showToast({
						title: '上传图片失败',
						icon: 'none',
						mask: true,
						duration: 1000
					})
				})
		},
		fail: (err) => {
			console.log('读取文件失败', err)
			uni.showToast({
				title: '读取文件失败',
				icon: 'none',
				mask: true,
				duration: 1000
			})
		}
	})
}

// logo裁剪确定
function logoHandleConfirm(event) {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	console.log('logo裁剪')
	const { tempFilePath } = event
	const fileSystemManager = uni.getFileSystemManager()
	let fileData
	fileSystemManager.readFile({
		filePath: tempFilePath, // 图片临时路径
		success: async (data) => {
			console.log('data', data)
			fileData = data.data
			// uploadFile(src, file).then((data) => {
			// 	resolve(data);
			// });
			await upLoadFileApi(tempFilePath)
				.then((res) => {
					console.log('上传头像res', res)
					let rData = JSON.parse(res.data)
					console.log('rData', rData)
					companyFormData.value.logoUrl = rData.data
					uni.hideLoading()
				})
				.catch((err) => {
					console.log('上传图片err', err)
					uni.showToast({
						title: '上传图片失败',
						icon: 'none',
						mask: true,
						duration: 1000
					})
				})
		},
		fail: (err) => {
			console.log('读取文件失败', err)
			uni.showToast({
				title: '读取文件失败',
				icon: 'none',
				mask: true,
				duration: 1000
			})
		}
	})
}

function imgLoaderror(res) {
	console.log('加载失败', res)
}

function imgLoaded(res) {
	console.log('加载成功', res)
}

function handleCancel(event, t) {
	console.log('取消', t, event)
}

// 地址输入框change事件
const addressChange = (e) => {
	// console.log('e',e);
	personalFormData.value.lat = ''
	personalFormData.value.lng = ''
}

// 选择位置点击事件
const selectLocation = () => {
	uni.chooseLocation({
		success: (res) => {
			console.log('选择位置res', res)
			personalFormData.value.companyAddress = res.name
			personalFormData.value.lat = res.latitude
			personalFormData.value.lng = res.longitude
		},
		fail: (err) => {
			console.log('选择位置err', err)
		}
	})
}

// 行业选择数据
const industrySelectData = ref([])

// 行业选择确定事件
const industryConfirm = (e) => {
	console.log('e', e)
	personalFormData.value.industry = e.value
}

// 个人资料保存点击事件
const userSaveClick = () => {
	/* 非空校验 ------------------------------------------------------ */
	// 头像
	if (personalFormData.value.avatar == '') {
		uni.showToast({
			title: '必须选择头像',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}
	// 姓名
	if (personalFormData.value.name == '') {
		uni.showToast({
			title: '姓名不能为空',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}
	// 职位
	if (personalFormData.value.position == '') {
		uni.showToast({
			title: '职位不能为空',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}
	// 手机号
	if (personalFormData.value.phone == '') {
		uni.showToast({
			title: '手机号不能为空',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}
	// 公司名称
	if (personalFormData.value.companyName == '') {
		uni.showToast({
			title: '公司名称不能为空',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}
	// 公司地址
	if (personalFormData.value.companyAddress == '') {
		uni.showToast({
			title: '公司地址不能为空',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}
	// 公司所属行业
	if (personalFormData.value.industry == '') {
		uni.showToast({
			title: '必须选择行业',
			icon: 'none',
			mask: true,
			duration: 1000
		})
		return
	}

	let data = {
		userId: userStore.userInfo.userId,
		cardUserProfilePicture: personalFormData.value.avatar,
		cardUserName: personalFormData.value.name,
		cardUserPosition: personalFormData.value.position,
		cardUserPhone: personalFormData.value.phone,
		cardUserWx: personalFormData.value.wxNumber,
		cardUserWxImage: personalFormData.value.wxQrCode,
		cardUserEmail: personalFormData.value.email,
		cardUserIntroduce: personalFormData.value.selfIntroduction,
		companyName: personalFormData.value.companyName,
		industryName: personalFormData.value.industry,
		companyAddress: personalFormData.value.companyAddress,
		companyWebsite: personalFormData.value.officialWebsite,
		longitude: personalFormData.value.lng,
		latitude: personalFormData.value.lat
	}
	console.log('保存个人资料', data)
	// 判断是创建还是修改
	console.log('userStore.isCreateBusinessCard', userStore.isCreateBusinessCard)
	if (userStore.isCreateBusinessCard) {
		console.log('修改个人资料')
		data.cardUserId = personalFormData.value.cardUserId
		editCardUserFunc(data)
	} else {
		console.log('创建个人资料')
		addCardUserFunc(data)
	}
}

// 图片路径字符串转换数组
const imgUrlStrToArr = (str) => {
	let arr = str.split(',')
	return arr
}

// 数组转换图片路径字符串
const arrToImgUrlStr = (arr) => {
	let str = arr.join(',')
	return str
}

// 将请求的数据转换成内部数据
const reqDataToMyData = (data) => {
	let nData = []
	nData = data.map((itemD) => {
		return {
			id: itemD.introduceId,
			title: itemD.introduceTitle,
			contentText: itemD.introduceContent,
			contentImages: imgUrlStrToArr(itemD.introduceImage)
		}
	})
	return nData
}

const myDataToReqData = (data) => {
	let nData = []
	nData = data.map((itemD) => {
		return {
			// introduceId: itemD.id,
			introduceTitle: itemD.title,
			introduceContent: itemD.contentText,
			introduceImage: arrToImgUrlStr(itemD.contentImages)
		}
	})
	return nData
}

// 企业资料保存点击事件
const companySaveClick = () => {
	let isDisFlag = true
	// 判断产品介绍是否填写完整
	if (cardStore.productIntroduceList.length == 0) {
		let data = {
			userId: userStore.userInfo.userId,
			companyLogo: companyFormData.value.logoUrl,
			introduceList: []
		}
		// 判断是创建还是修改
		if (currentCompanyId.value != null && currentCompanyId.value != undefined && currentCompanyId.value != '') {
			console.log('修改企业资料')
			editCardCompanyFunc(data)
		} else {
			console.log('添加企业资料')
			addCardCompanyFunc(data)
		}
	} else {
		cardStore.productIntroduceList.forEach((item, index) => {
			if (item.introduceTitle.trim() == '' || item.introduceUrl.trim() == '') {
				isDisFlag = false
				uni.showToast({
					title: `请将产品介绍${index + 1}信息填写完整`,
					mask: true,
					icon: 'none',
					duration: 1000
				})
			} else {
				isDisFlag = true
			}
		})

		if (isDisFlag) {
			let data = {
				userId: userStore.userInfo.userId,
				companyLogo: companyFormData.value.logoUrl,
				introduceList: []
			}
			// 判断是创建还是修改
			if (currentCompanyId.value != null && currentCompanyId.value != undefined && currentCompanyId.value != '') {
				console.log('修改企业资料')
				editCardCompanyFunc(data)
			} else {
				console.log('添加企业资料')
				addCardCompanyFunc(data)
			}
		}
	}
}

/* 请求函数 start ------------------------------------------------------------------- */

// 创建个人资料的函数
const addCardUserFunc = async (data) => {
	await addCardUserApi(data)
		.then((res) => {
			if (res.data.result == 'success') {
				console.log('创建个人资料res', res)
				uni.showToast({
					title: '保存成功',
					mask: true,
					icon: 'none',
					duration: 1000
				})
				userStore.isCreateBusinessCard = true
			} else if (res.data.result == 'error') {
				console.log('创建个人资料err', res)
				uni.showToast({
					title: '保存失败',
					mask: true,
					icon: 'none',
					duration: 1000
				})
			}
		})
		.catch((err) => {
			console.log('创建个人资料err', err)
			uni.showToast({
				title: '保存失败',
				mask: true,
				icon: 'none',
				duration: 1000
			})
		})
}

// 创建企业资料的函数
const addCardCompanyFunc = async () => {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	let data = {
		userId: userStore.userInfo.userId,
		companyLogo: companyFormData.value.logoUrl,
		introduceList: myDataToReqData(cardStore.companyIntroduceList)
	}
	await addCardCompanyApi(data)
		.then((res) => {
			if (res.data.result == 'success') {
				console.log('创建企业资料res', res)
				uni.showToast({
					title: '保存成功',
					mask: true,
					duration: 1000,
					icon: 'none'
				})
				selectCardCompanyFunc()
			} else if (res.data.result == 'error') {
				console.log('创建企业资料err', res)
				uni.showToast({
					title: '保存失败',
					mask: true,
					duration: 1000,
					icon: 'none'
				})
				selectCardCompanyFunc()
			}
		})
		.catch((err) => {
			console.log('创建企业资料err', err)
		})
}

// 修改个人资料的函数
const editCardUserFunc = async (data) => {
	await editCardUserApi(data)
		.then((res) => {
			if (res.data.result == 'success') {
				console.log('修改个人资料res', res)
				uni.showToast({
					title: '保存成功',
					mask: true,
					duration: 1000,
					icon: 'success'
				})
			} else if (res.data.result == 'error') {
				console.log('修改个人资料err', res)
			}
		})
		.catch((err) => {
			console.log('修改个人资料err', err)
		})
}

// 修改企业资料的函数
const editCardCompanyFunc = async () => {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	let productIntroduceListR = cardStore.productIntroduceList.map((item) => {
		return {
			introduceTitle: item.introduceTitle,
			introduceUrl: item.introduceUrl
		}
	})
	let data = {
		companyId: currentCompanyId.value,
		userId: userStore.userInfo.userId,
		companyLogo: fileList1.value[0].url,
		introduceList: myDataToReqData(cardStore.companyIntroduceList),
		productIntroduceList: productIntroduceListR
	}
	console.log('修改企业资料data', data)
	await editCardCompanyApi(data)
		.then((res) => {
			if (res.data.result == 'success') {
				console.log('修改企业资料res', res)
				uni.showToast({
					title: '保存成功',
					icon: 'none',
					mask: true,
					duration: 1000
				})
				selectCardCompanyFunc()
			} else if (res.data.result == 'error') {
				console.log('修改企业资料err', res)
				uni.showToast({
					title: '保存失败',
					icon: 'none',
					mask: true,
					duration: 1000
				})
				selectCardCompanyFunc()
			}
		})
		.catch((err) => {
			console.log('修改企业资料err', err)
		})
}

// 经纬度查询填充函数
const lngAdnLatRet = (value) => {
	let dataL = ''
	if (value == '' || value == null || value == undefined || value == 'null' || value == 'undefined') {
		dataL = ''
	} else {
		dataL = value
	}
	return dataL
}

// 查询个人资料的函数
const selectCardUserFunc = async () => {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	await selectCardUserApi(userStore.userInfo.userId)
		.then((res) => {
			if (res.data.result == 'success') {
				console.log('查询个人资料res', res)
				personalFormData.value = {
					avatar: res.data.data.cardUserProfilePicture,
					name: res.data.data.cardUserName,
					position: res.data.data.cardUserPosition,
					phone: res.data.data.cardUserPhone,
					wxNumber: res.data.data.cardUserWx,
					wxQrCode: res.data.data.cardUserWxImage,
					email: res.data.data.cardUserEmail,
					selfIntroduction:
						res.data.data.cardUserIntroduce == '' || res.data.data.cardUserIntroduce == null || res.data.data.cardUserIntroduce == undefined
							? '业务范围：饮用水安全监测 | 实验室定量分析 | 水环境质量监测 | 工业工程在线监测 | 污水排放水质监测 产品及解决方案咨询'
							: res.data.data.cardUserIntroduce,
					companyName: '浙江陆恒环境科技有限公司',
					companyAddress: res.data.data.companyAddress,
					industry: '制造业',
					officialWebsite: 'www.lohand.com',
					cardUserId: res.data.data.cardUserId,
					lat: lngAdnLatRet(res.data.data.latitude),
					lng: lngAdnLatRet(res.data.data.longitude)
				}
				uni.hideLoading()
			} else if (res.data.result == 'error') {
				console.log('查询个人资料err', res)
			}
		})
		.catch((err) => {
			console.log('查询个人资料err', err)
		})
}

// 是否创建企业资料的标识
const isCreateCompany = ref(false)

// 查询企业资料的函数
const selectCardCompanyFunc = async () => {
	// uni.showLoading({
	// 	title: '加载中',
	// 	mask: true
	// })
	await selectCardCompanyApi(userStore.userInfo.userId)
		.then((res) => {
			if (res.data.result == 'success') {
				console.log('查询企业资料res', res)
				if (res.data.data == null) {
					console.log('未创建企业资料')
					cardStore.companyIntroduceList = []
					companyFormData.value.logoUrl = ''
					currentCompanyId.value = null
					cardStore.currentCompanyId = null
					isCreateCompany.value = false
				} else {
					isCreateCompany.value = true
					companyFormData.value.logoUrl = res.data.data.companyLogo
					cardStore.productIntroduceList = res.data.data.productIntroduceList
					fileList1.value = [
						{
							url: res.data.data.companyLogo
						}
					]
					console.log('fileList1.value', fileList1.value)

					currentCompanyId.value = res.data.data.companyId
					cardStore.currentCompanyId = res.data.data.companyId
					if (res.data.data.introduceList == null) {
						console.log('未创建企业介绍')
						cardStore.companyIntroduceList = []
					} else {
						cardStore.companyIntroduceList = reqDataToMyData(res.data.data.introduceList)
					}
				}
				// uni.hideLoading()
			} else if (res.data.result == 'error') {
				console.log('查询企业资料err', res)
			}
		})
		.catch((err) => {
			console.log('查询企业资料err', err)
		})
}

/* 请求函数 end ------------------------------------------------------------------- */

onMounted(() => {
	let industrySelect = []
	jsonData.industryList.forEach((item) => {
		industrySelect.push(item.industryName)
	})
	industrySelectData.value = industrySelect

	console.log('userStore', userStore.userInfo.userId)
	console.log('userStore', userStore.isCreateBusinessCard)

	// 判断是否已经创建过，如果已经创建，再去查询数据
	if (userStore.isCreateBusinessCard) {
		selectCardUserFunc()
		selectCardCompanyFunc()
	}

	// setInterval(function () {
	// 	console.log('personalFormData.value.industry', personalFormData.value.industry)
	// }, 1000)
	
	
	// getAccess_token()
})
</script>

<style lang="scss" scoped>
:deep(.wd-tabs) {
	.wd-tabs__nav {
		.wd-tabs__nav--wrap {
			.wd-tabs__nav-container {
				.wd-tabs__nav-item {
					font-size: 15px !important;
				}
			}
		}
	}
}

:deep(.loading-wrap) {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

:deep(.wd-img) {
	width: 100%; /* 图片宽度设置为 100% */
	height: auto; /* 图片高度自动调整 */

	.wd-img__image {
		width: 100%; /* 图片宽度设置为 100% */
		height: auto; /* 图片高度自动调整 */
	}
}

:deep(.logo_upload) {
	width: 90px !important;
	height: 90px !important;
}

:deep(.wd-icon) {
	// padding-left: 10px;
}

:deep(.logo_upload .wd-icon::before) {
	position: relative;
	left: 30%;
	transform: translateX(-50%);
}

:deep(.logo_upload .wd-upload__picture) {
	width: 50px !important;
	height: 50px !important;
}

:deep(.logo_upload .wd-upload__evoke-num) {
	display: none !important;
}

:deep(.name_input.wd-input__inner) {
	// width: 100vw !important;
	width: 100%;
	height: 39px;
	padding: 0px 6px 0px 6px;
	flex: none !important;
	text-align: left !important;
	border-bottom: 0.4px solid rgba(#ccc, 0.6);
}

:deep(.url_input.wd-input__inner) {
	// width: 100vw !important;
	width: 100%;
	height: 40px;
	padding: 0px 6px 0px 6px;
	flex: none !important;
	text-align: left !important;

	border: none !important;
}

:deep(.url_input.wd-input__inner:focus) {
	border: none !important;
}

.tel_num_right_box {
	display: flex;
	flex-direction: column;
	height: 60px;
	// position: relative;
	justify-content: end;
}

:deep(.getPhone_btn){
	// margin-right: 10px !important;
	// padding: 0px 20px;
	// position: absolute;
	// right: 0;
	// left: 16px;
	// top: 30px;
	transform: scale(0.8);
	margin: 0 0 0 100px;
	width: 130px;
	position: relative;
	left: 20px;
	top: 6px;
}

// :deep(.phone_input){
// 	position: relative;
// }
</style>
